package com.aynu.account.tools;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedisTools {
    @Autowired
    private StringRedisTemplate redisTemplate;
    int expireTime=10;
    public int addErrorTry(String userId){
        ValueOperations<String, String> svo = redisTemplate.opsForValue();
        String s = svo.get(userId);
        if(s == null){
            svo.set(userId,"1");
            redisTemplate.expire(userId,expireTime, TimeUnit.MINUTES);
            return 4;
        }
        int newErrorTry = Integer.parseInt(s)+1;
        svo.set(userId, String.valueOf(newErrorTry));
        redisTemplate.expire(userId,expireTime, TimeUnit.MINUTES);
        return 5-newErrorTry;
    }
    public boolean allowTry(String userId){
        ValueOperations<String, String> svo = redisTemplate.opsForValue();
        String s = svo.get(userId);
        if(s == null){
            return true;
        }
        return Integer.parseInt(s) != 5;
    }
    public void removeErrorTry(String userId){
        ValueOperations<String, String> svo = redisTemplate.opsForValue();
        String s = svo.get(userId);
        if(s == null){
            return;
        }
        redisTemplate.delete(userId);
    }
}
